<template>
  <movie-header-backup></movie-header-backup>
  
  <!-- Movie Detail Hero Section -->
  <section class="relative min-h-[40vh] flex items-center justify-center text-center px-4 overflow-hidden mt-16">
    <div class="absolute inset-0 bg-gray-900 opacity-90 z-0"></div>
    <div class="absolute top-4 left-4 z-20">
      <button 
        class="px-4 py-2 bg-gradient-to-r from-purple-600 to-blue-600 text-white rounded-full hover:from-purple-700 hover:to-blue-700 transition-all duration-300 shadow-lg"
        @click="backToContent"
      >
        <i class="fas fa-arrow-left mr-2"></i> 返回
      </button>
    </div>
    <div class="max-w-6xl mx-auto relative z-10 flex flex-row md:flex-row md:items-start gap-12" v-if="movie">
      <!-- Movie Poster 左侧图片 -->
      <div style="flex:0 0 400px;display:flex;align-items:flex-start;justify-content:center;">
        <div class="relative overflow-hidden rounded-xl shadow-2xl glow-effect">
          <img 
            :src="getPosterUrl(movie.posterName)" 
            alt="Movie Poster" 
            class="w-full max-w-[400px] mx-auto md:mx-0 transform hover:scale-105 transition-transform duration-300"
          />
        </div>
      </div>
  
      <!-- Movie Info 右侧详情 -->
      <div class="text-left flex-1 flex flex-col justify-start items-start bg-white/10 rounded-xl p-10 min-w-[350px] max-w-[700px]" style="backdrop-filter: blur(2px);">
        <h1 class="text-5xl md:text-6xl font-extrabold mb-8 text-white">
          <span class="gradient-text">{{ movie.movieName }}</span>
        </h1>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 text-gray-200 w-full text-xl">
          <div class="flex items-center">
            <i class="fas fa-star text-yellow-400 mr-3 text-2xl"></i>
            <span><b>评分：</b><span class="text-2xl text-yellow-300 font-bold">{{ movie.rate }}</span></span>
          </div>
          <div class="flex items-center">
            <i class="fas fa-film text-blue-400 mr-3 text-2xl"></i>
            <span><b>类型：</b>{{ transformGerne(movie.genre) }}</span>
          </div>
          <div class="flex items-center">
            <i class="far fa-calendar-alt text-green-400 mr-3 text-2xl"></i>
            <span><b>上映时间：</b>{{ movie.showTime }}</span>
          </div>
          <div class="flex items-center">
            <i class="fas fa-user-friends text-purple-400 mr-3 text-2xl"></i>
            <span><b>演员：</b>{{ movie.actors }}</span>
          </div>
        </div>
      </div>
    </div>
  </section>
  
  <!-- Movie Summary Section -->
  <section class="py-12 bg-gray-900">
    <div class="max-w-4xl mx-auto px-4">
      <h2 class="text-3xl font-bold mb-6 gradient-text inline-block">内容梗概</h2>
      <div class="bg-gray-800 rounded-xl p-6 shadow-lg">
        <p class="text-gray-300 leading-relaxed">{{ movie?.summary }}</p>
      </div>
    </div>
  </section>
  
  <!-- Cinemas Section -->
  <section class="py-12 bg-gray-800">
    <div class="max-w-7xl mx-auto px-4">
      <h2 class="text-3xl font-bold mb-8 gradient-text inline-block">上映院线列表</h2>
      
      <!-- Cinemas Grid -->
      <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
        <div 
          v-for="(cinema, index) in cinemas" 
          :key="index"
          class="bg-gray-900 rounded-xl overflow-hidden shadow-lg card-hover-effect"
        >
          <div class="relative overflow-hidden">
            <img 
              :src="getPictureUrl(cinema.cinemaId)" 
              alt="Cinema Picture" 
              class="w-full h-48 object-cover transition-transform duration-500 hover:scale-110"
            />
            <div class="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent"></div>
          </div>
          <div class="p-4">
            <h3 class="text-lg font-bold text-white mb-2 truncate">{{ cinema.cinemaName }}</h3>
            <p class="text-gray-400 text-sm mb-2">
              <i class="fas fa-map-marker-alt mr-1"></i> {{ cinema.location }}
            </p>
            <p class="text-yellow-400 font-bold mb-4">
              <i class="fas fa-ticket-alt mr-1"></i> 价格：{{ cinema.ticketPrice }}￥/张
            </p>
            <button 
              class="w-full py-2 bg-gradient-to-r from-pink-500 to-purple-500 text-white rounded-lg hover:from-pink-600 hover:to-purple-600 transition-all duration-300"
              @click="buyTicket(cinema)"
            >
              <i class="fas fa-shopping-cart mr-1"></i> 购票
            </button>
          </div>
        </div>
      </div>
    </div>
  </section>
  
  <ticket-modal
    v-model:modelValue="dialogVisible"
    :cinemaId="cinemaId"
    :movieId="movieId"
    :userId="userId"
    :ticketPrice="curCinema?.ticketPrice"
    v-if="dialogVisible">
  </ticket-modal>
  
  <movie-footer></movie-footer>
</template>

<script>
import axios from 'axios';
import MovieFooter from './MovieFooter.vue';
import MovieHeaderBackup from './MovieHeaderBackup.vue';
import config from '@/config';
import TicketModal from './TicketModal.vue';

export default {
  components: {
    MovieFooter,
    MovieHeaderBackup,
    TicketModal
  },
  data() {
    return {
      dialogVisible: false,
      movie: null,
      movieId:null,
      userId:null,
      curCinema:null,
      cinemas: [],
      cinemaId: null,
      gerneDir: ["动作", "剧情", "喜剧", "恐怖", "科幻", "爱情", "惊悚", "动画",
        "纪录片", "奇幻", "冒险", "悬疑", "犯罪", "音乐", "战争", "传记"
      ]
    };
  },
  created(){
    this.fetchUserId();
    this.fetchMovieDetail();
    this.fetchCinemasByMovie();
  },
  methods:{
    async fetchUserId() {
      try {
        const response = await axios.post(`/user/getUserInfo`);
        if (response.data.code == 200) {
          const data = response.data.data;
          this.userId = data.userId;
        }
      } catch (error) {
        console.log(error);
      }
    },
    async fetchMovieDetail() {
      this.movieId = this.$route.params.movieId;
      try {
        const response = await axios.get(`${config.url}movie/${this.movieId}`);
        if (response.data.code === 200) {
          this.movie = response.data.data;
        } else {
          alert('Failed to fetch movie details');
        }
      } catch (error) {
        console.error('Error fetching movie details:', error);
      }
    },
    async fetchCinemasByMovie(){
      try{
          const response = await axios.post(`${config.url}movie/getCinemasByMovie/${this.movieId}`);
          if (response.data.code === 200) {
            this.cinemas = response.data.data;
            for (const cinema of this.cinemas) {
              cinema.ticketPrice = this.calTicketPrice(cinema.ticketPrices, this.movieId);
            }
          }

        }catch(error){
          console.error('Error fetching movies by cinema:', error);
        }
    },
    getPosterUrl(posterName) {
      return require(`@/assets/img/movie_posts/${posterName}`);
    },
    backToContent(){
      this.$router.push("/");
    },
    getPictureUrl(cinemaId) {
      return require(`@/assets/img/cinema/cinema${cinemaId}.jpg`);      
    },
    async buyTicket(cinema){
      if (!this.userId) {
        this.$router.push("/login");
        return;
      }
      this.dialogVisible = true;
      this.curCinema = cinema;
      this.cinemaId = cinema.cinemaId;
    },
    /**
     * 
     * @param { string } priceStr 
     * @param { number } movieId 
     */
    calTicketPrice(priceStr, movieId) {
      let price = 0;
      let strs = priceStr.split(',');
      for (const s of strs) {
        const movie_price = s.split(':');
        const id = +movie_price[0];
        if (movieId == id) {
          price = +movie_price[1];
          break;
        }
      }
      return price;
    },
    transformGerne(genreNum) {
      return this.gerneDir[genreNum - 1];
    }
  }
};
</script>

<style scoped>
.transition-transform {
  transition-property: transform;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 500ms;
}

.hover\:scale-110:hover {
  transform: scale(1.1);
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.leading-relaxed {
  line-height: 1.625;
}
</style>
